package com.cmlite.connect;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.cmlite.model.EventModel;
import com.cmlite.model.EventModelList;
import com.cmlite.model.OutLogin;
import com.cmlite.model.OutResult;
import com.cmlite.model.PeopleModel;
import com.cmlite.model.PeopleModelList;
import com.cmlite.model.Profile;
import com.cmlite.util.ConnectionException;
import com.cmlite.util.EmptyDataException;
import com.cmlite.util.TokenUnableException;
import com.cmlite.util.Util;

public class CallApi {
	public static final String SERVER = "https://regform.guncms.de/cmlite/cmlite/api";
	public static final String REST_LOGIN = "login";
	public static final String REST_LOGOUT = "logout";
	public static final String REST_POST_REGISTRY = "registry";

	public static final String REST_EVENTS = "events";
	// public static final String REST_

	public static final String JSON_NULL = "Data empty !";
	private static final String TAG = CallApi.class.toString();

	private static String getString(JSONObject jsonObject, String name) {
		String tmp;
		try {
			tmp = jsonObject.isNull(name) ? "" : jsonObject.getString(name);
			if (tmp == null)
				tmp = "";
		} catch (JSONException e) {
			tmp = "";
			e.printStackTrace();
		}
		return tmp;
	}

	public static OutLogin getLogin(Context context, String username,
			String pass, String org) throws EmptyDataException,
			ConnectionException, JSONException, TokenUnableException {
		OutLogin result = new OutLogin();

		HTTPReq htreq = new HTTPReq(SERVER);
		String url = "/" + REST_LOGIN + "/" + username + "/" + pass;
		Log.e("SON getLogin", url);
		HashMap<String, String> hashMap = new HashMap<String, String>();
		hashMap.put("organization", org);
		String json = htreq.post(context, url, hashMap);
		result = parserLogin(json);
		return result;
	}

	private static OutLogin parserLogin(String json) {
		OutLogin a = new OutLogin();
		try {
			JSONObject c = new JSONObject(json);
			a.setMessage(getString(c, OutResult.MESSAGE));
			a.setCode(getString(c, OutResult.CODE));
			a.setStatus(getString(c, OutResult.STATUS));
			if (a.getStatus()) {
				a.setReson(getString(c, OutResult.RESON));
				a.setToken(getString(c, "token"));
				
				Profile outProfile = new Profile();
				JSONObject jsonObject = new JSONObject(getString(c, "profile"));

				outProfile.setUsername(getString(jsonObject, "username"));
				outProfile.setFirst_name(getString(jsonObject, "first_name"));
				outProfile.setLast_name(getString(jsonObject, "last_name"));
				outProfile.setEmail(getString(jsonObject, "email"));
				a.setProfile(outProfile);
			} else {
				a.setReson(getString(c, OutResult.RESON));
				a.setMessage(getString(c, OutResult.MESSAGE));
				return a;
			}
		} catch (Exception ex) {
			a.setStatus(false);
			a.setMessage("Error :" + ex.getMessage());
			ex.printStackTrace();
		}

		return a;
	}
    public static OutResult postLogout(Context context,String token) throws EmptyDataException, ConnectionException, JSONException, TokenUnableException{
    	OutResult result = new OutResult();
		HTTPReq htreq = new HTTPReq(SERVER);
		String format = String.format("/logout/%s", token);
		HashMap<String, String> hashMap = new HashMap<String, String>();
		String json = htreq.post(context, format, hashMap);
		result = parserRegister(json);
		return result;
    }
	public static OutResult postRegister(Context context, String organization,
			String firstname, String lastname, String email, String password,
			String birthday, String plz, String stadt,String address)
			throws EmptyDataException, ConnectionException, JSONException,
			TokenUnableException {
		OutResult result = new OutResult();

		HTTPReq htreq = new HTTPReq(SERVER);
		String url = "/" + REST_POST_REGISTRY;
		HashMap<String, String> hashMap = new HashMap<String, String>();
		hashMap.put("organization", organization);
		hashMap.put("first_name", firstname);
		hashMap.put("last_name", lastname);
		hashMap.put("email", email);
		hashMap.put("password", password);
		hashMap.put("properties[address]", address);
		hashMap.put("properties[birthday]", birthday);
		hashMap.put("properties[plz]", plz);
		hashMap.put("properties[stadt]", stadt);
		Util.logParam(hashMap);
		String json = htreq.post(context, url, hashMap);
		result = parserRegister(json);
		return result;
	}

	private static OutResult parserRegister(String json) {
		OutResult a = new OutResult();
		try {
			JSONObject c = new JSONObject(json);
			a.setMessage(getString(c, OutResult.MESSAGE));
			a.setCode(getString(c, OutResult.CODE));
			a.setStatus(getString(c, OutResult.STATUS));
			if (a.getStatus()) {
				a.setReson(getString(c, OutResult.RESON));
			} else {
				a.setReson(getString(c, OutResult.RESON));
				a.setMessage(getString(c, OutResult.MESSAGE));
				return a;
			}
		} catch (Exception ex) {
			a.setStatus(false);
			a.setMessage("Error :" + ex.getMessage());
			ex.printStackTrace();
		}
		return a;
	}

	public static EventModelList getEvents(Context context, String token,
			int maxitem, int offset, String filter, String order, String keyword)
			throws EmptyDataException, ConnectionException, JSONException,
			TokenUnableException {
		EventModelList result = new EventModelList();
		String format = null;
		if (filter != null && !filter.equalsIgnoreCase("")) {
			format = String.format("events/%s/%d/%d/%s/%s", token, maxitem,
					offset, filter, order);
		} else {
			format = String.format("events/%s", token);
		}
		HTTPReq htreq = new HTTPReq(SERVER);
		String url = "/" + format;

		HashMap<String, String> hashMap = new HashMap<String, String>();
		hashMap.put("keyword", keyword);
		String json = htreq.post(context, url, hashMap);
		result = parserListEvent(json);

		return result;
	}

	private static EventModelList parserListEvent(String json) {
		EventModelList list = new EventModelList();
		try {
			JSONObject c = new JSONObject(json);
			list.setMessage(getString(c, OutResult.MESSAGE));
			list.setStatus(getString(c, OutResult.STATUS));
			list.setCode(getString(c, OutResult.CODE));
			if (!list.getStatus()) {
				list.setReson(getString(c, OutResult.RESON));
			} else {
				JSONArray array = c.getJSONArray("events");
				for (int i = 0; i < array.length(); ++i) {
					JSONObject jsonObject = array.getJSONObject(i);
					EventModel event = new EventModel();
					event.setEventId(jsonObject.getString("EID"));
					event.setEventName(jsonObject.getString("Evname"));
					event.setEventOrt(jsonObject.getString("evtOrt"));
					list.addItem(event);
				}
			}
		} catch (Exception ex) {
			list.setStatus(false);
			list.setMessage("Error :" + ex.getMessage());
			ex.printStackTrace();
		}
		return list;

	}

	public static PeopleModelList getPeopleListOfEvent(Context context,
			String token, String eventId, int maxitem, int offset,
			String filter, String order, String keyword)
			throws EmptyDataException, ConnectionException, JSONException,
			TokenUnableException {
		PeopleModelList list = new PeopleModelList();
		String format = "";
		if (filter != null && !filter.equalsIgnoreCase("")) {
			format = String.format("peoples/%s/%s/%d/%d/%s/%s", token, eventId,
					maxitem, offset, filter, order);
		} else {
			format = String.format("peoples/%s/%s", token, eventId);
		}
		HTTPReq htreq = new HTTPReq(SERVER);
		String url = "/" + format;
		HashMap<String, String> hashMap = new HashMap<String, String>();
		hashMap.put("keyword", keyword);
		String json = htreq.post(context, url, hashMap);
		list = parserListPeopleFor(json);
		return list;
	}

	private static PeopleModelList parserListPeopleFor(String json) {
		PeopleModelList list = new PeopleModelList();

		try {
			JSONObject c = new JSONObject(json);
			list.setMessage(getString(c, OutResult.MESSAGE));
			list.setStatus(getString(c, OutResult.STATUS));
			list.setCode(getString(c, OutResult.CODE));
			if (!list.getStatus()) {
				list.setReson(getString(c, OutResult.RESON));
			} else {
				JSONObject objectJson = c.getJSONObject("people_more_labels");
				// get list label ;
				JSONArray array = objectJson.getJSONArray("labels");
				list.lables = new String[array.length()];
				for (int i = 0; i < array.length(); ++i) {
					list.lables[i] = array.getString(i);
				}
				// get list key
				array = objectJson.getJSONArray("keys");
				list.key = new String[array.length()];
				for (int i = 0; i < array.length(); ++i) {
					list.key[i] = array.getString(i);
				}
				// get list event
				array = c.getJSONArray("peoples");
				for (int i = 0; i < array.length(); ++i) {
					JSONObject jsonObject = array.getJSONObject(i);
					PeopleModel peoples = new PeopleModel();
					peoples.setmPeople_ID(jsonObject.getString("Persid"));
					peoples.setmField_01(jsonObject.getString(list.key[0]));
					peoples.setmField_02(jsonObject.getString(list.key[1]));
					peoples.setmField_03(jsonObject.getString(list.key[2]));
					peoples.setmField_04(jsonObject.getString(list.key[3]));
					peoples.setmField_05(jsonObject.getString(list.key[4]));
					peoples.setCheck(jsonObject.getString("checkbox").equals("1") ? true : false);
					list.addItem(peoples);
				}
			}
		} catch (Exception ex) {
			list.setStatus(false);
			list.setMessage("Error :" + ex.getMessage());
			ex.printStackTrace();
		}
		return list;

	}

	public static OutResult addPeople(Context context, String token,
			String event_id, String[] key, String[] value)
			throws EmptyDataException, ConnectionException, JSONException,
			TokenUnableException {
		HashMap<String, String> hashMap = new HashMap<String, String>();
		for (int i = 0; i < key.length; ++i) {
			hashMap.put(key[i], value[i]);
		}
		String format = String.format("add_people/%s/%s", token, event_id);

		HTTPReq htreq = new HTTPReq(SERVER);
		String url = "/" + format;

		String json = htreq.post(context, url, hashMap);
		return parserAddPeople(json);

	}

	private static OutResult parserAddPeople(String json) {
		OutResult a = new OutResult();
		try {
			JSONObject c = new JSONObject(json);
			a.setMessage(getString(c, OutResult.MESSAGE));
			a.setStatus(getString(c, OutResult.STATUS));
			a.setCode(getString(c, OutResult.CODE));
			if (a.getStatus()) {
				a.setReson(getString(c, OutResult.RESON));
				JSONObject peopleObj = c.getJSONObject("people");
				PeopleModel p = new PeopleModel();
				p.setmPeople_ID(peopleObj.getString("Persid"));
				a.setmPeople(p);
			} else {
				a.setReson(getString(c, OutResult.RESON));
				a.setMessage(getString(c, OutResult.MESSAGE));
				return a;
			}
		} catch (Exception ex) {
			a.setStatus(false);
			a.setMessage("Error :" + ex.getMessage());
			ex.printStackTrace();
		}
		return a;
	}

	public static OutResult editPeople(Context context, String token,
			String event_id, String people_id, String[] key, String[] value)
			throws EmptyDataException, ConnectionException, JSONException,
			TokenUnableException {
		HashMap<String, String> hashMap = new HashMap<String, String>();
		for (int i = 0; i < key.length; ++i) {
			hashMap.put(key[i], value[i]);
		}
		String format = String.format("edit_people/%s/%s/%s", token, event_id,
				people_id);

		HTTPReq htreq = new HTTPReq(SERVER);
		String url = "/" + format;

		String json = htreq.post(context, url, hashMap);
		return parserEditPeople(json);

	}

	private static OutResult parserEditPeople(String json) {
		OutResult a = new OutResult();
		try {
			JSONObject c = new JSONObject(json);
			a.setMessage(getString(c, OutResult.MESSAGE));
			a.setStatus(getString(c, OutResult.STATUS));
			a.setCode(getString(c, OutResult.CODE));
			if (a.getStatus()) {
				a.setReson(getString(c, OutResult.RESON));
			} else {
				a.setReson(getString(c, OutResult.RESON));
				a.setMessage(getString(c, OutResult.MESSAGE));
				return a;
			}
		} catch (Exception ex) {
			a.setStatus(false);
			a.setMessage("Error :" + ex.getMessage());
			ex.printStackTrace();
		}
		return a;
	}

	public static OutResult deletePeople(Context context, String token,
			String event_id, String people_id, String[] key, String[] value)
			throws EmptyDataException, ConnectionException, JSONException,
			TokenUnableException {
		HashMap<String, String> hashMap = new HashMap<String, String>();
		for (int i = 0; i < key.length; ++i) {
			hashMap.put(key[i], value[i]);
		}
		String format = String.format("delete_people/%s/%s/%s", token,
				event_id, people_id);

		HTTPReq htreq = new HTTPReq(SERVER);
		String url = "/" + format;

		String json = htreq.post(context, url, hashMap);
		return parserDeletePeople(json);

	}

	private static OutResult parserDeletePeople(String json) {
		OutResult a = new OutResult();
		try {
			JSONObject c = new JSONObject(json);
			a.setMessage(getString(c, OutResult.MESSAGE));
			a.setStatus(getString(c, OutResult.STATUS));
			a.setCode(getString(c, OutResult.CODE));
			if (a.getStatus()) {
				a.setReson(getString(c, OutResult.RESON));
			} else {
				a.setReson(getString(c, OutResult.RESON));
				a.setMessage(getString(c, OutResult.MESSAGE));
				return a;
			}
		} catch (Exception ex) {
			a.setStatus(false);
			a.setMessage("Error :" + ex.getMessage());
			ex.printStackTrace();
		}
		return a;
	}

	public static OutResult getPeopleListOfEvent(Context context,
			String token, String event_id, HashMap<String, String> hashMapPram)
			throws EmptyDataException, ConnectionException, JSONException,
			TokenUnableException {
		OutResult list = new OutResult();
		String format = String.format("save_peoples/%s/%s", token, event_id);
		HTTPReq htreq = new HTTPReq(SERVER);
		String url = "/" + format;
		Log.d(TAG,hashMapPram.toString()); 
		String json = htreq.post(context, url, hashMapPram);
		list = parserRegister(json);
		return list;
	}

}